<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>车辆评论管理</span>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model="queryParams.carId" placeholder="请输入车辆ID" clearable />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-select v-model="queryParams.rating" placeholder="请选择评分" clearable>
            <el-option v-for="i in 5" :key="i" :label="i + '星'" :value="i" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容关键词" prop="content">
          <el-input v-model="queryParams.content" placeholder="请输入关键词" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @refresh="getList"></right-toolbar>
      </el-row>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="commentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="评论ID" align="center" prop="commentId" />
        <el-table-column label="车辆ID" align="center" prop="carId" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="评论内容" align="center" prop="content" :show-overflow-tooltip="true" />
        <el-table-column label="评分" align="center" prop="rating">
          <template #default="scope">
            <el-rate v-model="scope.row.rating" disabled text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-show="total > 0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="commentForm" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="车辆ID" prop="carId">
            <el-input v-model="form.carId" placeholder="请输入车辆ID" />
          </el-form-item>
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="form.userId" placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="评论内容" prop="content">
            <el-input v-model="form.content" type="textarea" placeholder="请输入评论内容" />
          </el-form-item>
          <el-form-item label="评分" prop="rating">
            <el-rate v-model="form.rating" :max="5" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllComments, getCommentById, addComment, updateComment, deleteComment, searchComments } from '@/api/comment'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 评论表格数据
const commentList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  carId: undefined,
  userId: undefined,
  rating: undefined,
  content: undefined
})

// 表单参数
const form = reactive({
  commentId: undefined,
  carId: undefined,
  userId: undefined,
  content: '',
  rating: 5
})

// 表单校验
const rules = {
  carId: [
    { required: true, message: "车辆ID不能为空", trigger: "blur" }
  ],
  userId: [
    { required: true, message: "用户ID不能为空", trigger: "blur" }
  ],
  content: [
    { required: true, message: "评论内容不能为空", trigger: "blur" }
  ],
  rating: [
    { required: true, message: "评分不能为空", trigger: "blur" }
  ]
}

// 解析时间
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

/** 查询评论列表 */
const getList = async () => {
  loading.value = true
  try {
    // 这里应该根据实际接口做分页处理，如果后端不支持，可以在前端处理
    // 这里简单处理，实际应该传入分页参数
    const response = await getAllComments()
    commentList.value = response || []
    total.value = commentList.value.length
  } catch (error) {
    ElMessage.error("获取评论列表失败")
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNum = 1
  loading.value = true
  try {
    const response = await searchComments(queryParams)
    commentList.value = response || []
    total.value = commentList.value.length
  } catch (error) {
    ElMessage.error("搜索评论失败")
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.carId = undefined
  queryParams.userId = undefined
  queryParams.rating = undefined
  queryParams.content = undefined
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.commentId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true
  title.value = "添加评论"
  form.commentId = undefined
  form.carId = undefined
  form.userId = undefined
  form.content = ''
  form.rating = 5
}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  const commentId = row.commentId
  const response = await getCommentById(commentId)
  if (!response) {
    ElMessage.error("获取评论信息失败")
    return
  }
  
  Object.assign(form, response)
  open.value = true
  title.value = "修改评论"
}

/** 提交按钮 */
const submitForm = async () => {
  try {
    if (form.commentId) {
      // 修改
      const response = await updateComment(form)
      if (response) {
        ElMessage.success("修改成功")
        open.value = false
        getList()
      } else {
        ElMessage.error("修改失败")
      }
    } else {
      // 新增
      const response = await addComment(form)
      if (response) {
        ElMessage.success("新增成功")
        open.value = false
        getList()
      } else {
        ElMessage.error("新增失败")
      }
    }
  } catch (error) {
    ElMessage.error("操作失败")
    console.error(error)
  }
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const commentIds = row.commentId || ids.value
  if (!commentIds || (Array.isArray(commentIds) && !commentIds.length)) {
    ElMessage.warning("请选择要删除的评论")
    return
  }
  
  ElMessageBox.confirm('是否确认删除评论?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      // 如果是数组，需要循环删除，这里简单处理
      if (Array.isArray(commentIds)) {
        // 实际可能需要批量删除API
        for (const id of commentIds) {
          await deleteComment(id)
        }
      } else {
        await deleteComment(commentIds)
      }
      getList()
      ElMessage.success("删除成功")
    } catch (error) {
      ElMessage.error("删除失败")
      console.error(error)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
const handleExport = () => {
  // 实际导出功能，需要根据后端API进行调整
  ElMessage.info("导出功能开发中")
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb8 {
  margin-bottom: 8px;
}
</style> 